﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace CRL.DBAccess
{
    public partial class SqlHelper
    {
        public override async Task InsertFromDataTableAsync(DataTable dataTable, string tableName, bool keepIdentity = false)
        {
            SqlBulkCopy sqlBulkCopy;
            var option = keepIdentity ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.KeepNulls;
            option = option | SqlBulkCopyOptions.FireTriggers;
            if (_trans != null)
            {
                SqlTransaction sqlTrans = _trans as SqlTransaction;
                sqlBulkCopy = new SqlBulkCopy(currentConn as SqlConnection, option, sqlTrans);
            }
            else
            {
                GetOrCreateConn();
                sqlBulkCopy = new SqlBulkCopy(currentConn as SqlConnection, option, null);
            }
            sqlBulkCopy.DestinationTableName = tableName;
            sqlBulkCopy.BatchSize = dataTable.Rows.Count;
            if (dataTable != null && dataTable.Rows.Count != 0)
            {
                await sqlBulkCopy.WriteToServerAsync(dataTable);
            }
            sqlBulkCopy.Close();
        }
    }
}
